package cn.edu.hitsz.core;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Map;

import org.apache.log4j.Logger;

import cn.edu.hitsz.conf.FileConfig;
import cn.edu.hitsz.conf.SpiderConfig;

/**
 * FILE CONNECTION TO WRITE DATA TO LOCAL FILE SYSTEM
 * 
 * @author mingchen
 * @date 2015年8月9日
 */
public class FileConnection extends Connection {
	private final static Logger LogClass = Logger.getLogger(SpiderConfig.class);
	private final FileConfig fcnf;
	private  Map<String, String> map;

	/**
	 * 
	 * Constructor function of Class
	 * 
	 * @param fcnf
	 *            FileConfig
	 * @param map
	 *            Data in map
	 */
	public FileConnection(FileConfig fcnf, Map<String, String> map) {
		this.fcnf = fcnf;
		this.map = map;
	}
	public FileConnection(FileConfig fcnf){
		this.fcnf = fcnf;
		map = null;
	}
	
	/**
	 * Set the map to configuration
	 * 
	 * @param map
	 *            void 2015年8月17日下午3:30:57
	 */
	@Override
	public void setMap(Map<String,String> map){
		this.map = map;
	}
	
	/**
	 * Offer the map data to configuration and write the data
	 * 
	 * @param map
	 *            void 2015年8月17日下午3:32:14
	 */
	@Override
	public boolean offerData(Map<String, String> map) {
		this.map = map;
		write();
		return true;
	}
	/**
	 * Implement of interface method
	 */
	@Override
	public void write() {
		File dir = fcnf.getFile();
		for (String key : map.keySet()) {
			String[] files = key.split(":");
			LogClass.info("Write to file"+dir+"\\"+files[0]+"\\"+files[1]+"["+map.get(key).length()+"]");
			BufferedWriter bw = null;
			try{
				bw = new BufferedWriter(new FileWriter(dir.getPath()+"/"+files[0]+"/"+files[1]));
			}catch(Exception e){
				e.printStackTrace();
			}
			writeContent(bw, map.get(key));

		}

	}

	/**
	 * Write content to file
	 * 
	 * @param bw
	 * @param content
	 *            void 2015年8月9日
	 */
	private void writeContent(BufferedWriter bw,String content){
		try{
			bw.write(content);
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
